package com.briup.cms.service.impl;

import com.briup.cms.bean.BaseUser;
import com.briup.cms.constant.CmsConstants;
import com.briup.cms.dao.extend.BaseUserExtendMapper;
import com.briup.cms.exception.CustomerException;
import com.briup.cms.service.IBaseUserService;
import com.briup.cms.utils.JwtUtil;
import com.briup.cms.utils.MessageStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 用户服务层
 */
@Service
public class BaseUserServiceImpl implements IBaseUserService {
	@Autowired
	private BaseUserExtendMapper baseUserExtendMapper;

	@Override
	public String login(String username, String password) throws CustomerException {
		BaseUser user = baseUserExtendMapper.findUserByName(username);

		if(user==null){
			throw new CustomerException(MessageStatus.USER_NOT_EXIST);
		}

		if(user.getStatus() != CmsConstants.USER_STATUS_NORMAL){
			throw new CustomerException(MessageStatus.USER_ACCOUNT_FORBIDDEN);
		}

		if(user.getRole() != CmsConstants.SYSTEM_ROLE_ADMIN){
			throw new CustomerException(MessageStatus.PERMISSION_NOT_ADMIN);
		}

		if(!user.getPassword().equals(password)){
			throw new CustomerException(MessageStatus.USER_LOGIN_ERROR);
		}

		Map<String,Object> map = new HashMap<>();
		map.put("username",user.getUsername());
		map.put("realname",user.getRealname());
		String token = JwtUtil.sign(user.getUserId().toString(),map);

		return token;

	}
}
